package gps.util;


import gps.Colour;
import gps.Parameters;
import gps.Square;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.StringTokenizer;

public class BoardGenerator {

	public static Square[][] getRandomMatrix() {
		Random generator = new Random( 19580427 );
		
		Square[][] gameBoard = new Square[Parameters.BOARD_SIZE][Parameters.BOARD_SIZE];
		
		for (int i=0; i<Parameters.BOARD_SIZE; i++) {
			for (int j=0; j<Parameters.BOARD_SIZE; j++) {
				gameBoard[i][j] = new Square(Colour.values()[generator.nextInt(Colour.values().length)],i,j);
			}
		}
		
		return gameBoard;
	}
	
	public static Square[][] readFromFile() {
		Square[][] board = null;
		Colour[] colours;
		BufferedReader br;
		StringTokenizer strtok;
		String boardRow, boardAsString = "";
		int dimension = 0;
		
		try {
			
			InputStream is = BoardGenerator.class.getResourceAsStream("/board.txt");
			br = new BufferedReader(new InputStreamReader(is));
			
			while((boardRow = br.readLine()) != null) {
				boardRow = boardRow.trim();
				boardAsString += boardRow;
				// assume board is squared, then number of rows = number of cols
				boardAsString += "\n";
				dimension++; 
			}
			
			strtok = new StringTokenizer(boardAsString);
			board = new Square[dimension][dimension];
			colours = Colour.values();

			for (int i = 0 ; i < dimension ; i++) {
				for (int j = 0 ; j < dimension ; j++) {
					board[i][j] = new Square(colours[Integer.valueOf(strtok.nextToken())-1], i, j);
				}
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return board;
	}
}
